package com.qf.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qf.base.BaseServlet;
import com.qf.model.Cart;
import com.qf.model.CartItem;
import com.qf.model.Product;

/**
 * Servlet implementation class CartServlet
 */
public class CartServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
  
	protected void cart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;utf-8");
		String pid = request.getParameter("pid");
		
		int buyNum = Integer.parseInt(request.getParameter("number"));
		Product p = productServiceImpl.findByPid(pid);
		
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart==null){
			cart = new Cart();
		}
		Map<String, CartItem> cartItem = cart.getCartItem();
		CartItem item = new CartItem();
		if(cartItem.containsKey(pid)){
			item = cartItem.get(pid);
			item.setBuyNum(item.getBuyNum()+buyNum);
			item.setSubTotal((int) (item.getSubTotal()+p.getShop_price()*buyNum));
		}else{
			item.setBuyNum(buyNum);
			item.setProduct(p);
			item.setSubTotal((int) (p.getShop_price()*buyNum));
		}
		cartItem.put(pid, item);
		
		cart.setCartItem(cartItem);
	    cart.setTotal(cart.getTotal()+p.getShop_price()*buyNum);
	    
		request.getSession().setAttribute("cart", cart);
		response.sendRedirect("cart.jsp");
	}
        
	
	protected void deleteProductFromCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;utf-8");
		String pid = request.getParameter("pid");
		Product p = productServiceImpl.findByPid(pid);
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart!=null){
		   Map<String, CartItem> cartItem = cart.getCartItem();
		   double subTotal = cartItem.get(pid).getSubTotal();
		   cart.setTotal(cart.getTotal()-subTotal);
		   cartItem.remove(pid);
		}
		request.getSession().setAttribute("cart", cart);
		response.sendRedirect("cart.jsp");
		
	}


}
